//
//  GBNetWorking+encrypt.m
//  乡易秀商户端
//
//  Created by delicious on 17/9/7.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "GBNetWorking+encrypt.h"
#import "DES3Util.h"
#import "NSData+ASE128.h"

static NSString *const version = @"1.0.0";
static NSString *const iphone = @"iphone";
@implementation GBNetWorking (encrypt)
-(NSDictionary *)onGetSignParamForParam:(NSDictionary *)param
{
 
    // 添加相同的参数 ---- 参与排序的
    NSMutableDictionary *mParam = [[NSMutableDictionary alloc] initWithDictionary:param];
    [mParam setObject:version forKey:@"version"];
    [mParam setObject:iphone forKey:@"client"];
    
    // key
    NSArray * arr = [mParam allKeys];
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch;
    // 排序条件
    NSComparator sort = ^(NSString *obj1,NSString *obj2){
        NSRange range = NSMakeRange(0,obj1.length);
        return [obj1 compare:obj2 options:comparisonOptions range:range];
    };
    // 排序后的key数组
    NSArray * result = [arr sortedArrayUsingComparator:sort];
    // 键值对拼接
    NSMutableArray * marr = [NSMutableArray new];
    for (NSString * key in result) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,mParam[key]]];
    }
    // 拼接字符串
    NSMutableString * mStr = [NSMutableString new];
    
    //当前时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    //转为字符型取整数部分
    NSString *senddate = [NSString stringWithFormat:@"%.0f", a];
    
    [mStr appendFormat:@"%@%@%@",KSign_key,Ksign_sec,senddate];
    for (NSString * str in marr) {
        if (str == marr[result.count - 1]) {
            [mStr appendFormat:@"%@",str];
        }
        else
            [mStr appendFormat:@"%@&",str];
    }
    
       NSLog(@"签名参数            %@",mStr);
    // 签名
    NSString * sign = [self MD5ForText:mStr];   //sign
    
    // 拼接字符串
    //    NSMutableString * mparamStr = [NSMutableString new];
    //     [mparamStr appendFormat:@"app_key=%@&timestamp=%@&sign=%@&",APP_KEY_MD5,[NSDate UNIXDate],sign];
    //    for (NSString * str in marr) {
    //        if (str == marr[result.count - 1]) {
    //            [mparamStr appendFormat:@"%@",str];
    //        }
    //        else
    //            [mparamStr appendFormat:@"%@&",str];
    //    }
    
    NSMutableDictionary * mdic = [NSMutableDictionary new];
    [mdic setObject:KSign_key forKey:@"app_key"];
    [mdic setObject:senddate forKey:@"timestamp"];
    [mdic setObject:sign forKey:@"sign"];
    [mdic addEntriesFromDictionary:mParam];
    
    return mdic;

}
-(NSString *)jsonStringForParam:(NSDictionary *)param{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (jsonData == nil) {
#ifdef DEBUG
        NSLog(@"fail to get JSON from dictionary: %@, error: %@", param, error);
#endif
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}


-(NSString *)MD5ForText:(NSString *)text
{
    const char* original_str=[text UTF8String];
    //CC_MD5_DIGEST_LENGTH = 16
    unsigned char digist[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(original_str, (int)strlen(original_str), digist);
    
    NSMutableString* outPutStr = [NSMutableString stringWithCapacity:10];
    
    for(int  i =0; i<CC_MD5_DIGEST_LENGTH;i++){
        //小写x表示输出的是小写MD5，大写X表示输出的是大写MD5
        [outPutStr appendFormat:@"%02x", digist[i]];
    }
    return [outPutStr lowercaseString];
    
}




-(NSDictionary *)onAES128EncryptForParam:(NSDictionary *)param
{
    NSString *signDicString = [self jsonStringForParam:param];
    NSLog(@"参数--->\n%@",signDicString);
    NSString *base64Data =[DES3Util AES128Encrypt:signDicString withKey:KAes_key iv:KAes_iv];

    if (!base64Data) {
        return nil;
    }
    return @{@"data":base64Data};
}

//-(NSDictionary *)onSetNewParam:(NSDictionary *)param
//{
//    NSDictionary *dic = [self onGetSignParamForParam:param];
//    
//    return [self onAES128EncryptForParam:dic];
//}

-(id)onSetUpdateParam:(NSDictionary *)param
{
   NSDictionary *dic = [self onGetSignParamForParam:param];
    
    return [self onAES128EncryptForParam:dic];
}
@end
